package com.asia.algorithmcode.binaryTree;

/**
 * @DESCRIPTION: 129、求根节点到叶子节点数字之和
 * @USER: wanfu
 * @DATE: 2025/6/10 星期二 15:38
 */
public class SumNumbers {


    public static void main(String[] args) {
        TreeNode t4 = new TreeNode(4);
        TreeNode t9 = new TreeNode(9);
        TreeNode t0 = new TreeNode(0);
        TreeNode t5 = new TreeNode(5);
        TreeNode t1 = new TreeNode(1);

        t4.left = t9;
        t4.right = t0;
        t9.left = t5;
        t9.right = t1;

        System.out.println(new SumNumbers().sumNumbers(t4));
    }


    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode root, int preValue) {
        if (root == null) {
            return 0;
        }
        int sum = preValue * 10 + root.val;

        if (root.left == null && root.right == null) {
            return sum;
        } else {
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
    }


}
